import config from '../configuration.js';
import fetch from 'node-fetch';
import redisHelper from '../redisHelper.js';

async function GetOpenID(code) {
    // let pa = await getPAInfo(appid);
    // if (pa == null) {
    //     console.warn(`获取小程序信息失败，未查询到对应的小程序信息 appid: ${appid}`);
    //     return { code: 1, msg: '未查询到对应的小程序信息' };
    // }
    // let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.applet_param.APPID}&secret=${config.applet_param.APPSECRET}&code=${code}&grant_type=authorization_code`;
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.applet_param.APPID}&secret=${config.applet_param.APPSECRET}&js_code=${code}&grant_type=authorization_code`;
    try {
        let res = await _get(url);
        console.info('获取OpenID成功', `请求URL==>${url}  响应==>${res}`);
        return { code: 1, data: JSON.parse(res) };
    } catch (error) {
        console.error(console.log('用Code获取OpneID出错', `请求URL==>${url}`, error.message));
        return { code: 0, msg: '用Code获取OpneID出错:' + error.message };
    }
}
async function _get(url) {
    let response = await fetch(url);
    let result = await response.text();
    return result;
}

class WxService {
    static async getAccessToken() {
        const accssTokenKey = `wx_access_token`;
        const expires = 6000;
        const accessTokenKey = await redisHelper.get(accssTokenKey);
        if (accessTokenKey) {
            return accessTokenKey;
        }

        const ret = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
            params: {
                grant_type: 'client_credential',
                appid: config.applet_param.APPID,
                secret: config.applet_param.APPSECRET,
            },
        });

        if (!ret.data?.access_token) {
            logger.info('微信获取token失败', ret);
            return;
        }

        await redisHelper.set(accssTokenKey, ret.data.access_token, expires);
        return ret.data.access_token;
    }

    static async generateUrllink(params) {
        const accessToken = await this.getAccessToken();
        const ret = await axios.post(
            'https://api.weixin.qq.com/wxa/generate_urllink',
            {
                ...params,
            },
            {
                params: {
                    access_token: accessToken,
                },
            }
        );
        return ret.data;
    }
}

export { GetOpenID, WxService };
